import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import easyDAO.SqlDispatch;
import models.*;
import tools.ReadProperties;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Date;
import java.util.Objects;

/**
 * Created by yangxianming on 2018/1/16.
 * 设备数据上传测试
 */
@WebServlet(name = "login", urlPatterns = {"/login/*"}, loadOnStartup = 2)
public class Login extends HttpServlet {
    MyConfig myConfig = new MyConfig();
    public void init(ServletConfig config) throws ServletException {
        ReadProperties readProperties = new ReadProperties(config.getServletContext().getRealPath("/"));
        myConfig.setPropertiesConfig(readProperties);
        myConfig.setSplitMark();
        myConfig.setUser(new User());
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //start
        long start = new Date().getTime();

        response.setHeader("Content-type", "text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        String returnInfo = "";

        //首字母大写
//        char[] cs = request.getPathInfo().substring(1).toCharArray();
//        cs[0] -= 32;

        Class<?> action;
        try {
            ReturnJson rj = new ReturnJson();
            HttpSession sh = request.getSession();
            String username = request.getParameter("username");
            String password = request.getParameter("password");
            System.out.println("user: " + username + ", try login!");

            if (username.equals("POWERLIST")){
                rj.setErrorMsg("无法登陆");
                rj.setApiStatus(0);
                out.print(rj.toString());
            }

            SqlDispatch sqlDispatch = new SqlDispatch(myConfig);
            //拿到用户数据
            String sql1 = "SELECT username, password,power FROM `user` WHERE username = \""+username+"\"";
            SqlReturnModel srm = sqlDispatch.selectWord(sql1);
            //验证密码
            if (checkUser(srm, password)){
                Cookie[] cookies = request.getCookies();
                if (Objects.equals(null, cookies)){
                    rj.setResult("../../");
                }else {
                    for (Cookie cookie: cookies){
                        if (Objects.equals(cookie.getName(), "JSESSIONID")){
                            User user = new User();
                            user.setUsername(username);
                            user.setSessionId(cookie.getValue());
                            user.setPower(getPower(srm));
                            sh.setAttribute(cookie.getValue(), user);
                            rj.setResult("/html/home.html");
                        }
                    }
                }
            }else {
                rj.setErrorMsg("用户名或密码错误");
                rj.setApiStatus(0);
            }
            returnInfo = rj.toString();

//            action = Class.forName("videoBusiness." + String.valueOf(cs));
//            Method method = action.getDeclaredMethod("doIt", HttpServletRequest.class, MyConfig.class);
//            returnInfo = (String)method.invoke(action.newInstance(), request, myConfig);
        }catch (Exception e){
            e.printStackTrace();
        }

        //end
        long end = new Date().getTime();
        System.out.println(request.getRequestURI() + "; run time: " + (end-start) + "ms");

        out.print(returnInfo);
    }

    @Override
    public void destroy()
    {
        // 什么也不做
    }

    private JSONArray getPower(SqlReturnModel srm){
        //通过与admin的权限做比对生成页面权限
        ArrayList<ArrayList<String>> userInfo = srm.getSelectReturnData();
        JSONObject jo = JSON.parseObject(userInfo.get(0).get(2));
        return jo.getJSONArray("apiPower");
    }

    private boolean checkUser(SqlReturnModel srm, String passWord){
        ArrayList<ArrayList<String>> userInfo = srm.getSelectReturnData();
        if (userInfo.size() == 0){
            //用户名没有退出
            return false;
        }
        if (!Objects.equals(Md5.md5PlusSalt(passWord), userInfo.get(0).get(1))){
            //密码不对退出
            return false;
        }
        return true;
    }
}
